package com.zxl.app.controller.order;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.zxl.app.context.UserContext;
import com.zxl.app.service.OrderService;
import com.zxl.common.Page;
import com.zxl.common.Result;
import com.zxl.common.exception.BusinessException;
import com.zxl.common.lock.BusinessLock;
import com.zxl.common.model.bo.order.CreateOrderBo;
import com.zxl.common.model.query.order.MyOrderListQuery;
import com.zxl.common.model.query.order.PayQuery;
import com.zxl.common.model.vo.order.OrderDetailsVo;
import com.zxl.common.model.vo.order.OrderList;
import com.zxl.common.service.SysOrderService;
import com.zxl.common.utils.HttpHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

/**
 * @author zxw
 * @date 2023/4/1
 */
@RestController
@RequestMapping("/app/order")
@Api(tags = {"订单模块"})
@Slf4j
public class OrderController {

    @Resource
    private OrderService orderService;


    @ApiOperation("订单列表")
    @GetMapping("/list")
    public Result<Page<OrderList>> list(MyOrderListQuery myOrderListQuery) {
        myOrderListQuery.setMemberId(UserContext.getUserId());
        List<OrderList> list = orderService.list(myOrderListQuery);
        Page<OrderList> page = Page.pageInfoConvert(new PageInfo(list));
        return new Result(page);
    }

    @ApiOperation("订单详情")
    @GetMapping("/details")
    public Result<OrderDetailsVo> getOrderDetails(@ApiParam(value = "订单编号", required = true) @RequestParam("orderCode") String orderCode) {
        OrderDetailsVo orderDetails = orderService.getOrderDetails(orderCode);
        return new Result(orderDetails);
    }

    @ApiOperation("/创建订单")
    @PostMapping("/create_order")
    public Result createOrder(@Valid @RequestBody CreateOrderBo createOrderBo) {
        createOrderBo.setMemberId(UserContext.getUserId());
        String orderCode = orderService.createOrder(createOrderBo);
        return Result.success(orderCode);
    }

    @ApiOperation("收货")
    @GetMapping("/complete")
    public Result complete(@ApiParam(value = "订单编号", required = true) @RequestParam("orderCode") String orderCode) {
        orderService.complete(orderCode, UserContext.getUserId());
        return Result.success();
    }

    @ApiOperation("取消订单")
    @GetMapping("/cancel")
    public Result cancel(@ApiParam(value = "订单编号", required = true) @RequestParam("orderCode") String orderCode) {
        orderService.cancel(orderCode, UserContext.getUserId());
        return Result.success();
    }

    @ApiOperation("微信支付")
    @PostMapping("/pay")
    public Result pay(@Valid @RequestBody PayQuery query) {
        try {
            String key = "order:pay:";
            return (Result) BusinessLock.newInstance().lock(key + query.getOrderCode(), () -> {
                query.setMemberId(UserContext.getUserId());
                return new Result<>(orderService.pay(query));
            });

        } catch (Exception e) {
            log.error("微信支付异常：" + e.getMessage());
            throw new BusinessException(e.getMessage());
        }

    }


    @ApiOperation("微信支付回调")
    @ApiIgnore
    @PostMapping("/pay_notice")
    public Result payNotice(HttpServletRequest request, HttpServletResponse response) {
        try {
            String reqParams = HttpHelper.getBodyString(request);
            log.info("-------支付结果:" + reqParams);
            JSONObject json = JSONObject.parseObject(reqParams);
            if (json.getString("event_type").equals("TRANSACTION.SUCCESS")) {
                log.info("-------支付成功");

            }
            orderService.payNotice(json);
            return Result.success();
        } catch (Exception e) {
            log.error("微信回调异常:" + e.getMessage());
            throw new BusinessException();
        }
    }


}
